package com.fengwuj.mutils.yml;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;

import java.util.Properties;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 修订记录：
 * jiangbo 2020/1/7 19:11 创建
 *
 * @author jiangbo
 */
@Configuration
@Slf4j
public class YmlConfigUtils {
    private static final int SCHEDULE_PERIORD = 30;
    private static final String FILENAME = "application.yml";

    private static Properties properties = new Properties();

    private static ScheduledExecutorService scheduled = Executors.newScheduledThreadPool(1);
    static {
        scheduled.scheduleAtFixedRate(() -> properties = getTypePropertie(), 0, SCHEDULE_PERIORD, TimeUnit.SECONDS);
    }


    /**
     * 获取yml文件中的值
     *
     * FILENAME yml文件名，需要在claspath目录下,classpath下直接传文件名，
     *        否则需要传递classpath下的相对路径，默认application.yml
     *      * @return
     */
    public static Properties getTypePropertie() {
        YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
        yaml.setResources(new ClassPathResource(FILENAME));
        properties = yaml.getObject();
        return properties;
    }

    public static String getStringProperty(String key){
        return properties.getProperty(key);
    }

    public static Integer getIntProperty(String key){
        String intString = properties.getProperty(key);
        if (StringUtils.isNotBlank(intString)){
            try {
                return Integer.valueOf(intString);
            }catch (Exception e){
                return -1;
            }
        }
        return -1;
    }

    public static Boolean getBooleanProperty(String key){
        String booleanString = properties.getProperty(key);
        if (StringUtils.isNotBlank(booleanString)){
            try {
                return Boolean.valueOf(booleanString);
            }catch (Exception e){
                return false;
            }
        }
        return false;
    }
}
